import ast
from ctypes.wintypes import tagMSG

import requests

import pandas as pd
import base64
import json
import os
import shutil
import time
import random
from collections import OrderedDict
from urllib.parse import quote_plus
import redis
import requests
from sqlalchemy import create_engine
from DrissionPage import ChromiumPage
from DrissionPage import ChromiumOptions
from DrissionPage.common import Settings
from DrissionPage.common import Keys
from DrissionPage.common import Actions
import pymysql
from DrissionPage.errors import *

import datetime


from mysql_ini import *
# from mysql_ini_ceshi import *
"""
https://customer.xiaohongshu.com/api/cas/customer/web/qr-code?service=https:%2F%2Fcreator.xiaohongshu.com&qr_code_id=68c517395516719772176435"""


class DOUYIN_LIFE:
    def __init__(self, user_id,account_id,order_id):
        self.CO = ChromiumOptions()  ##创建chrome实例
        # self.user_id = self.user_input()  ##用户
        self.user_id = str(user_id)  ##用户
        self.account_id = account_id
        self.order_id = order_id
        self.PORT = self.port_input()  ##chrome端口
        self.CO.set_paths(
            browser_path="browser_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")  ##chrome启动路径
        self.CO.set_local_port(self.PORT)  ##生成的端口 这里是手动生成
        self.CO.set_user_data_path(os.getcwd() + '/user_info_dir/{}'.format(self.user_id))  ##用户chrome文件夹
        # self.CO.arguments.append('--headless')
        self.ch = ChromiumPage(self.CO)

        self.ch.set.window.max()  ##chrome窗口最大化
        self.ac = Actions(self.ch)
        # self.fans = self.xhs_user_info_requests()
        # print(self.user_id)
        # self.redis_conn = redis.StrictRedis(host='r-bp162522qrwjh5e7jhpd.redis.rds.aliyuncs.com', port=6379,
        #                                     password='123sdmmh568%$#vs*!', db=21)
        # self.redis_conn = redis.StrictRedis(host='r-bp1y4wxs1fa8vxd1xspd.redis.rds.aliyuncs.com', port=6379,
        #                                     password='Jison0820', db=0)

    """根据用户ID查出端口号"""

    def port_fe(self):
        sql = "select spider_user_id,spider_port,spider_login_code from dy_life_center where spider_user_id='{}'".format(
            self.user_id)
        spider_config = self.pymysql_fetchall(sql)
        port = []
        for i in spider_config:
            port.append(i[1])

        return ''.join(port)

    """自动输入端口号"""

    def port_input(self):

        port1 = random.randint(5000, 9000)

        cc = self.port_jiance()
        while True:
            cc = self.port_jiance()
            if cc == "用户存在":
                # print("当前用户存在")
                port_ = self.port_fe()
                # print(port_)
                return port_
            if cc == "端口不存在":
                # print(port1)
                return port1
            else:
                return self.PORT

    """自动随机生成端口 并进行检测"""

    def port_jiance(self):
        port1 = random.randint(5000, 9000)

        sql = "select spider_user_id,spider_port,spider_login_code from dy_life_center"
        spider_config = self.pymysql_fetchall(sql)
        port_list = []
        # print(spider_config)
        for i in spider_config:
            port_list.append(i[1])
        user_exists = self.user_state()
        # print(user_exists, '************')
        if user_exists == "用户不存在":
            if port1 not in port_list:
                return "端口不存在"
            else:
                return "端口存在"
        else:
            return '用户存在'

    """查询数据库"""

    def pymysql_fetchall(self, sql):

        con = pymysql.connect(host=mysql_config_ini()["host"], port=mysql_config_ini()["port"], user=mysql_config_ini()["user"],
                              passwd=mysql_config_ini()["password"], db=mysql_config_ini()["database"], charset='utf8')
        # 获取操作数据的对象 cursor
        cursor = con.cursor()
        cursor.execute(sql)
        sql_result = cursor.fetchall()
        # 提交事务
        con.commit()
        # 关闭Cursor
        cursor.close()
        # 关闭链接
        con.close()

        return sql_result

    """从数据库判断用户是否存在"""

    def user_state(self):
        sql = "select spider_user_id,spider_port,spider_login_code from dy_life_center"
        result = self.pymysql_fetchall(sql)
        user_list = []
        for i in result:
            user_list.append(i[0])
        # print(user_list)
        if self.user_id in user_list:
            # print("存在")
            return "用户存在"
        else:
            return "用户不存在"

    """判断用户是否在数据库中 不在为新用户 在的话为老用户"""

    def user_info(self):
        engine2 = self.mysql_config()
        data_frame = pd.DataFrame([{"spider_user_id": str(self.user_id), "spider_port": str(self.PORT)}])
        # print(data_frame)
        # pd.io.sql.to_sql(data_frame, 'xhs_user_info', engine2, schema='live_data',if_exists='append',index=False)
        return data_frame

    # def mysql_config(self):
    #     user = 'live_data'
    #     password = quote_plus('CJMg2tsHg7sj6bo0UTKq0a4T!fPDpJ')
    #     # passwd ='merchantsasd123!@%&'
    #     host = 'rm-bp17r99475xuauk63yo.mysql.rds.aliyuncs.com'
    #     # port1 ='3306'
    #     dbname2 = 'live_data'
    #     engine2 = create_engine(f"mysql+pymysql://{user}:{password}@{host}:3306/{dbname2}?charset=utf8mb4")
    #     return engine2

    def mysql_config(self):
        user = mysql_config_ini()["user"]
        password = quote_plus(mysql_config_ini()["password"])
        # passwd ='merchantsasd123!@%&'
        host = mysql_config_ini()["host"]
        # port1 ='3306'
        dbname2 = mysql_config_ini()['database']
        engine2 = create_engine(f"mysql+pymysql://{user}:{password}@{host}:3306/{dbname2}?charset=utf8mb4")
        return engine2

    """修改用户登录状态的mysql"""

    def pymysql_update(self, sql, num):

        con = pymysql.connect(host=mysql_config_ini()["host"], port=mysql_config_ini()["port"], user=mysql_config_ini()["user"],
                              passwd=mysql_config_ini()["password"], db=mysql_config_ini()["database"], charset='utf8')
        # 获取操作数据的对象 cursor
        cursor = con.cursor()
        cursor.execute(sql, (num, self.user_id))
        # sql_result = cursor.fetchall()
        # 提交事务
        con.commit()
        # 关闭Cursor
        cursor.close()
        # 关闭链接
        con.close()

        return "用户{}状态修改成功,当前状态值为{}".format(self.user_id, num)


    """获取cookies"""

    def get_cookies(self):
        cookies_str = ''
        for i in self.ch.cookies(all_domains=False, all_info=True):
            my_ordered_dict = OrderedDict(i)

            # 取出前两个键值对
            first_two_items = list(my_ordered_dict.items())[:2]
            key_value_str = ''
            count_key_value = 0
            for i in first_two_items:
                count_key_value = count_key_value + 1
                if count_key_value == 1:
                    key_value_str = key_value_str + i[1] + '='
                else:
                    key_value_str = key_value_str + i[1]
            cookies_str = cookies_str + key_value_str + ";"
        return cookies_str

    def listen_shop_name_list(self):
        self.ch.refresh()
        self.ch.listen.start(
            'https://life.douyin.com/life/gate/v1/account/groupAccountList/?page_index=1&page_size=20&name=')

        shop_name_index = []
        life_account_id_list = []
        shop_name = '上海明牌首饰有限公司'
        for packet in self.ch.listen.steps(timeout=3):
            account_list = packet.response.body["data"]["list"]
            life_account_id = account_list[0]["detail"]["life_account_id"]
            life_account_id_list.append(life_account_id)
            # 使用 enumerate 遍历列表并查找索引
            for index, item in enumerate(account_list):
                if item['account_name'] == shop_name:
                    shop_name_index.append(index)
                    break  # 找到后退出循环
            else:
                print("未找到")  # 如果没有找到，则输出未找

        shop_name_index = shop_name_index[0] + 1

        ##选择账号下的店铺名称
        self.ch.ele(
            'xpath://*[@id="life_login_page"]/div[2]/div/div/div/div[2]/div/div[1]/div/div/div/div[{}]/div/div/div'.format(
                shop_name_index)).click()
        time.sleep(0.5)

        self.ch.ele('xpath://*[@id="life_login_page"]/div[2]/div/div/div/div[2]/div/div[2]/button').click()

        return life_account_id_list[0]

    # def listen_shop_name_list_id(self):
    #     self.ch.refresh()
    #     # time.sleep(5)
    #
    #     self.ch.listen.start('https://life.douyin.com/life/gate/v1/account/groupAccountList/')
    #
    #     shop_name_index = []
    #
    #     life_account_id_list = []
    #     shop_name = self.shop_name
    #     for packet in self.ch.listen.steps(timeout=30):
    #         account_list = packet.response.body["data"]["list"]
    #         print(account_list,"********账号名称列表********")
    #         for i in account_list:
    #             print(i,"********")
    #             if shop_name == i["account_name"]:
    #                 print(i)
    #                 life_account_id_list.append(i["detail"]["life_account_id"])
    #         # print(life_account_id_list[0])
    #     return life_account_id_list[0]

    def dlaike_order_finish(self):
        ###订单爬取完毕回调地址

        data = {
            "message": "rpa_douyin_order_complete"
        }

        ##正式环境
        url = 'https://www.jisonforest.com/prod-api/conversion/douyin/order/rpaConversionOrderResultCompleteWebhook'
        ##测试环境
        # url = "https://test.jisonforest.com/prod-api/conversion/douyin/order/rpaConversionOrderResultCompleteWebhook"

        com_refer = requests.post(url, json=data)
        print(com_refer.text)
        return "程序执行结束!!!!"

    def select_order_refer(self):
        time.sleep(3)
        cookies = self.get_cookies()
        headers = {"Cookie": cookies,
                   "referer": "https://life.douyin.com/p/liteapp/fulfillment-fusion/order?groupid=1765480014223375"}
        order_json_list = []
        main_list = []
        for order in self.order_id:
            print("订单ID",order)
            payload = {
                "filter": {
                    # "start_time": 1728576000,
                    # "end_time": 1729180799,
                    "product_option": [],
                    "order_id": order,
                    "is_market": False,
                    "is_market_poi": False,

                },
                "is_user_poi_filter": False,
                "industry": "industry_common",
                "permission_common_param": {}
            }
            url = 'https://life.douyin.com/life/trade_view/v1/sale/query/certificate_list/?page_index=1&page_size=20&industry=industry_common&root_life_account_id=%s' % self.account_id
            time.sleep(0.5)
            amount = requests.post(url, headers=headers, data=json.dumps(payload))
            amount_order = amount.json()["data"]["list"][0]
            # 订单编号
            order_id = amount_order["order_id"]
            # 订单状态{Status:1未核销 status:2已核销 status:4已退款}
            order_status = amount_order["status"]
            # 订单标签
            order_tag_name = amount_order["order_tag"][0]["tag_name"]
            ##订单标签类型
            order_tag_type = amount_order["order_tag"][0]["tag_type"]
            # 商品名称
            order_title = amount_order["sku"]["title"]
            # 商品图片
            order_image = amount_order["sku"]["image"]
            ##sku ID
            order_sku_id = amount_order["sku"]["sku_id"]
            ##支付时间
            order_pay_time = amount_order["pay_time"]
            ##商品原价
            crossed_amount = amount_order["amount"]["crossed_amount"]
            crossed_amount = float(crossed_amount) / 100

            ##售卖金额
            coupon_pay_amount = amount_order["amount"]['coupon_pay_amount']
            coupon_pay_amount = float(coupon_pay_amount) / 100

            ##订单实收金额
            pay_amount = amount_order["amount"]['pay_amount']
            pay_amount = float(pay_amount) / 100

            ##成交渠道
            sale_channel = amount_order["extra"]["attribute"]["sale_channel"]

            sale_user_nickname = amount_order["extra"]["attribute"]["sale_user_nickname"]

            video_share_url = amount_order["extra"]["attribute"]["video_share_url"]
            print(video_share_url)
            if 'share/video' in video_share_url:
                video_share_id = video_share_url.split('https://www.iesdouyin.com/share/video/')[1]
                print(video_share_id)
            if 'webcast/reflow/' in video_share_url:
                video_share_id = video_share_url.split('https://webcast.amemv.com/webcast/reflow/')[1]
                print(video_share_id)
            if '//user/profile/' in video_share_url:
                print("存在")
                video_share_id = video_share_url.split('//user/profile/')[1]
                print(video_share_id)

            if video_share_url == '':
                video_share_id = ''

            # 带货角色
            sale_user_role = amount_order["extra"]["attribute"]["sale_user_role"]

            order_json = {"random":self.user_id,"account_id":self.account_id,"order_id": order_id, "order_status": order_status, "title": order_title, "image": order_image,
                          "sku_id": order_sku_id, "pay_time": order_pay_time,
                          "crossed_amount": crossed_amount, "coupon_pay_amount": coupon_pay_amount,
                          "pay_amount": pay_amount, "order_tag_name": order_tag_name, "order_tag_type": order_tag_type,
                          "sale_channel": sale_channel, "sale_user_role": sale_user_role,
                          "sale_user_nickname": sale_user_nickname, "video_share_id": video_share_id}
            # print(order_json_list)
            order_json_list.append(order_json)

        # data_order_frame = pd.DataFrame(order_json_list)
        # pd.io.sql.to_sql(data_order_frame, 'dy_life_order_data', self.mysql_config(), schema='data-warehouse',
        #                  if_exists='append', index=False)
            if len(order_json_list) == 100:
                order_frame = pd.DataFrame(order_json_list)
                # order_frame["order_id"] = order_frame["order_id"].astype("int")
                # order_frame = order_frame.drop_duplicates(subset=["order_id"])
                pd.io.sql.to_sql(order_frame, 'conversion_order_result', mysql_config_order(),
                                 schema='conversion',
                                 if_exists='append',
                                 index=False)
                self.dlaike_order_finish()
                main_list.append(order_json_list[:])  # 使用[:]创建副本，避免后续修改影响主列表中的元素
                # 清空暂存列表以继续下一次攒集
                order_json_list.clear()


        if order_json_list:
            # main_list.append(order_json_list[:])
            print(order_json_list)
            print(len(order_json_list))
            order_frame_main = pd.DataFrame(order_json_list)
            order_frame_main["order_id"] = order_frame_main["order_id"].astype("int")
            order_frame_main = order_frame_main.drop_duplicates(subset=["order_id"])
            pd.io.sql.to_sql(order_frame_main, 'conversion_order_result', mysql_config_order(),
                             schema='conversion',
                             if_exists='append',
                             index=False)
            self.dlaike_order_finish()
        self.ch.close()
        return 'order_json_list'


    """用户不存在时，删除生成的指定的用户文件夹"""

    def delete_folder_random(self,random_id):
        try:
            shutil.rmtree(os.getcwd() + "\\user_info_dir\\" + random_id)
            print(f"成功删除文件夹")
        except OSError as e:
            print(f"删除文件夹失败")

    def dy_creator_center_spider(self):

        print('用户:', self.user_id, '此次的端口是:', self.PORT)
        data = pd.read_sql("select * from dlaike_user_info where dlaike_spider_user_id='{}'".format(self.user_id),self.mysql_config())
        if data.empty:
            self.ch.close()
            """删除指定的不存在的用户文件夹"""
            self.delete_folder_random(self.user_id)
            return {"code":500,"msg":"该用户不存在或未授权"}
        else:
            self.ch.get('https://life.douyin.com/p/login')
            time.sleep(6)
            # user_it_exist = self.user_state()
            # data_frame = self.user_info()
            # if user_it_exist == "用户不存在":
            #     data_frame["spider_login_code"] = '0'
            #     pd.io.sql.to_sql(data_frame, 'dy_life_center', self.mysql_config(), schema='data-warehouse',
            #                      if_exists='append', index=False)

            login_url_is = self.ch.url
            if login_url_is == "https://life.douyin.com/p/login":
                print("登陆过期")
                self.ch.close()
                return {"code":500,"msg":"登录状态已过期"}
                # self.ch.ele('xpath://*[@id="life_login_page"]/div[2]/div/div/div/div/div[3]/div[2]/div/form/div[1]/div/span/span[2]/label').input('18868750739\n')
                # time.sleep(0.5)

                # time.sleep(60)
                # ###获取验证码
                # time.sleep(2)
                # self.ch.ele('xpath://*[@id="life_login_page"]/div[2]/div/div/div/div/div[3]/div[2]/div/form/div[2]/div/span/label/span/span').click()
                #
                # time.sleep(5)

            # self.select_order_refer()
            # time.sleep(3)
            # douyin_life_id = self.listen_shop_name_list_id()
            # print(douyin_life_id)
            orderr_json = self.select_order_refer()
            # print(orderr_json)
            # self.ch.close()
            return orderr_json

# def main_result_dy_life():
#     dy_center = DOUYIN_LIFE(user_id='js_test_account_3',shop_name)
#     aa = dy_center.dy_creator_center_spider()


def mysql_config_test():
    user = mysql_config_ini()["user"]
    password = quote_plus(mysql_config_ini()["password"])
    # passwd ='merchantsasd123!@%&'
    host = mysql_config_ini()["host"]
    # port1 ='3306'
    dbname2 = mysql_config_ini()['database']
    engine2 = create_engine(f"mysql+pymysql://{user}:{password}@{host}:3306/{dbname2}?charset=utf8mb4")
    return engine2

# def mysql_config_order():
#     user = 'root'
#     password = 'Jison0820'
#     # passwd ='merchantsasd123!@%&'
#     host = 'rm-bp1be6s3581xp13rfco.mysql.rds.aliyuncs.com'
#     # port1 ='3306'
#     dbname2 = 'conversion'
#     engine2 = create_engine(f"mysql+pymysql://{user}:{password}@{host}:3306/{dbname2}?charset=utf8mb4")
#     return engine2


def mysql_config_order():
    user = 'warehouse'
    password = 'QlciCnfTB9NtLSC'
    # passwd ='merchantsasd123!@%&'
    host = 'rm-bp17709mm0o30s13r.mysql.rds.aliyuncs.com'
    # port1 ='3306'
    dbname2 = 'conversion'
    engine2 = create_engine(f"mysql+pymysql://{user}:{password}@{host}:3306/{dbname2}?charset=utf8mb4")
    return engine2

def expire_account_id(account_id,random_id,expire_time):

    ##测试环境
    # url = "https://test.jisonforest.com/prod-api/enterprise-admin/douyin/life/rpaAuthorizationOffline"

    ##正式环境
    url = 'https://www.jisonforest.com/prod-api/enterprise-admin/douyin/life/rpaAuthorizationOffline'
    data = {
    "account_id": account_id,
    "random": random_id,
    "expire_time": expire_time
    }
    expire_account_json = requests.post(url,json=data)
    print(expire_account_json.text)
    return expire_account_json.text
##where dlaike_spider_user_id='18268100534@telc316c61d47f64b14b54c1860734d106d'
##where dlaike_spider_user_id='trix-wang@email2315894193674ca7b28c4e0edc980682'

def sched_dlaike_order():
    data = pd.read_sql("select * from dlaike_user_info where dlaike_spider_user_id='770140258@emaildd5b0f5930e64ec68c8c162249a71013'",mysql_config_test())
    print(data)
    data_list = [data.loc[i].to_dict() for i in data.index.values]
    temp_list = []

    for i in data_list:
        # order_data = pd.read_sql("select distinct (douyin_order_id) from conversion_douyin_order where account_id='{}' limit 100".format(i["dlaike_id"]),mysql_config_order())
        # order_data = pd.read_sql("SELECT distinct (douyin_order_id) FROM conversion_douyin_order WHERE create_time >= CURDATE() - INTERVAL 1 DAY and account_id='{}'".format(i["dlaike_id"]),mysql_config_order())
        order_data = pd.read_sql("SELECT distinct (douyin_order_id) FROM conversion_douyin_order WHERE rpa_douyin_order_id='-1' and account_id='{}' limit 6000".format(i["dlaike_id"]),mysql_config_order())
        order_list = order_data["douyin_order_id"].tolist()

        # print(i)
        dy_center = DOUYIN_LIFE(user_id=i["dlaike_spider_user_id"],account_id=i["dlaike_id"],order_id=order_list)
        order_json = dy_center.dy_creator_center_spider()
        # print(order_json)
        if order_json == {"code":500,"msg":"登录状态已过期"}:
            current_time = datetime.datetime.now()

            print(expire_account_id(account_id=i["dlaike_id"], random_id=i["dlaike_spider_user_id"],
                                    expire_time=str(current_time)))
            print("登录过期")
        else:
            pass
            # temp_list.append(order_json)
            # print(len(order_json))

            # if len(order_json) == 10:
            #
            #     order_frame = pd.DataFrame(order_json)
            #     print(order_json)
            #     # order_frame["order_id"] = order_frame["order_id"].astype("int")
            #     # order_frame = order_frame.drop_duplicates(subset=["order_id"])
            #     pd.io.sql.to_sql(order_frame, 'conversion_order_result', mysql_config_order(),
            #                      schema='conversion',
            #                      if_exists='append',
            #                      index=False)








print(sched_dlaike_order())